//
//  DiaryViewController.m
//  Travel assistant
//
//  Created by lanou3g on 16/2/29.
//  Copyright © 2016年 旅游助手. All rights reserved.
//

#import "DiaryViewController.h"
#import "LableCollectionVCell.h"
#import "ImVCollectionVCell.h"
#import "MoodViewController.h"

@interface DiaryViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) TravelDiaryModel *travelDiaryModel;
@property (nonatomic, strong) NSMutableArray *diaryArray;
@property (nonatomic, strong) NSMutableArray *arrayAllData;


@end

@implementation DiaryViewController
static NSString *const lableCollectionVCell = @"LableCollectionVCell";
static NSString *const imVCollectionVCell = @"ImVCollectionVCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupData];
    [self setDelegate];
    [self setCollectionCellAttribute];
    [self setRegisterCollectionViewCell];
    
    // Do any additional setup after loading the view from its nib.1
    self.title = @"旅行日记";
    self.collectionView.backgroundColor = [UIColor colorWithRed:236 / 255.0 green:236 / 255.0 blue:236 / 255.0 alpha:0.9];
    
    [self.moodButton addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moodButtonAction:)]];
    [self.imVButton addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imVButtonAction:)]];
}

- (NSMutableArray *)arrayAllData
{
    if (!_arrayAllData) {
        _arrayAllData = [[NSMutableArray alloc] init];
    }
    return _arrayAllData;
}

- (void)setupData{
    AVQuery *query = [TravelDiaryModel query];
    /**排序*/
    [query orderByDescending:@"createdAt"];
    /**最多返回10条结果*/
    //query.limit = 10;
    /**跳过20条结果*/
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects.count) {
            NSArray<AVObject *> *diaryArray = objects;
            self.diaryArray = [NSMutableArray arrayWithArray:diaryArray];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
            
        } else {
            self.diaryArray = [NSMutableArray array];
        }
    }];
    
}
- (void)moodButtonAction:(UIView *)sender{
    NSLog(@"写心情。。。添加点击手势。。。。。");
    MoodViewController *moodVC = [[MoodViewController alloc] init];
    
    
    
    
    
    
    [self.navigationController pushViewController:moodVC animated:YES];
}
- (void)imVButtonAction:(UIView *)sender{
    NSLog(@"传照片。。。添加点击手势。。。。。");
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:@"选择照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [sheetController addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"召唤相册......");
        [self setImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
    }]];
    [sheetController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self setImagePickerController:UIImagePickerControllerSourceTypeCamera];
    }]];
    [sheetController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:sheetController animated:YES completion:nil];
    
}
- (void)setImagePickerController:(UIImagePickerControllerSourceType)source{
    /**1:初始化相册控制器*/
    self.imagePicker = [[UIImagePickerController alloc] init];
    /**2:设置代理*/
    self.imagePicker.delegate = self;
    /**3:图片来源*/
    self.imagePicker.sourceType = source;
    /**对图片大小位置选取*/
    [self.imagePicker setEditing:YES];
    self.imagePicker.allowsEditing = YES;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    /**选出已经选中的图片*/
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
//#pragma mark ---将图片压缩保存到CleanCloud---
////    CGSize imageSize = image.size;
////    /**设置图片大小*/
////    imageSize.height = 120;
////    imageSize.width = 60;
    /**经图片写入文件*/
    NSData *imageData = UIImagePNGRepresentation(image);
    AVFile *imageFile = [AVFile fileWithName:[NSString stringWithFormat:@"image.png"] data:imageData];
    //[imageFile save];
#pragma mark ---将图片文件imageFile保存到CleanCloud---
    self.travelDiaryModel = [TravelDiaryModel object];
    [self.travelDiaryModel setObject:imageFile forKey:@"notesImage"];
    [self.travelDiaryModel setObject:[NSString stringWithFormat:@"image"] forKey:@"notesType"];
    [self.travelDiaryModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"self.travelDiaryModel 保存成功...");
        } else {
            NSLog(@"%@",error);
        }
    }];
    /**模态推出*/
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)addAlertController{
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"请先登录......" message:@"确定" preferredStyle:UIAlertControllerStyleAlert];
    [alerController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alerController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"跳转到登陆界面......");
    }]];
    [self presentViewController:alerController animated:YES completion:nil];
}

-(void)setDelegate{
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
}










#pragma mark---------??????-------layout---怎么使用---
- (void)setCollectionCellAttribute{
//    /**用来给UICollectionView做布局用的*/
//    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//    /**属性*/
//    /**行间距 -> 最小值*/
//    layout.minimumLineSpacing = 0;
//    /**列间距 -> 最小值*/
//    layout.minimumInteritemSpacing = 0;
//    /**设置每块的大小*/
//    layout.itemSize = CGSizeMake((Screen_W - 40) / 3, (Screen_W - 40) / 3);
//    /**四边间距*/
//    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    
    
}
- (void)setRegisterCollectionViewCell{
    [self.collectionView registerNib:[UINib nibWithNibName:@"LableCollectionVCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:lableCollectionVCell];
    [self.collectionView registerNib:[UINib nibWithNibName:@"ImVCollectionVCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:imVCollectionVCell];
}
/**下面是与CollectionView有关的代理方法*/
- (NSInteger )collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.diaryArray.count;
}
- (NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TravelDiaryModel *travelDiaryModel = self.diaryArray[indexPath.row];
    NSString *type = [travelDiaryModel objectForKey:@"notesType"];
    NSLog(@"@@@@@@@%@",[travelDiaryModel objectForKey:@"notesType"]);
    
    if ([type isEqualToString:@"text"]) {
        LableCollectionVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:lableCollectionVCell forIndexPath:indexPath];
        

        cell.travelDiaryModel = travelDiaryModel;
        return cell;
    }
    ImVCollectionVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:imVCollectionVCell forIndexPath:indexPath];
    
    
    
    
    cell.travelDiaryModel = travelDiaryModel;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"--------%ld",indexPath.row);
    
    
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
- (CGSize )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((Screen_W - 40) / 3, (Screen_W - 40) / 3);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
